# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         user
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019-11-03
# -------------------------------------------------------------------------------

from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from apps.BasicAuthService.models import User

__all__ = ['UserAuthBackend']


class UserAuthBackend(ModelBackend):
    """
    自定义用户认证
    """

    @staticmethod
    def get_user_by_username(username=None):
        try:
            user = User.objects.get((Q(username=username) | Q(phone=username)), is_active=True)
        except User.DoesNotExist:
            user = None
        return user

    def authenticate(self, request, username=None, password=None, **kwargs):
        user = self.get_user_by_username(username=username)
        if isinstance(user, User) and user.check_password(password) and self.user_can_authenticate(user):
            return user
